package com.ilop.sthome.ui.activity.detail.common;

import android.util.Log;
import android.view.View;

import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.utils.LiveDataBus;
import com.example.common.view.refresh.CustomRefreshView;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SendAutoCommand;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DefaultBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.data.greenDao.SceneBean;
import com.ilop.sthome.mvp.contract.scene.SceneChangeContract;
import com.ilop.sthome.mvp.present.scene.SceneChangePresenter;
import com.ilop.sthome.ui.adapter.scene.SceneChangeAdapter;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.greenDao.utils.AutomationDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DefaultDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.tools.ByteUtil;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityModeSwitchBinding;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author skygge
 * @date 2019-12-11.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：添加自定义场景切换
 */
public class ModeSwitchActivity extends ContainLoginActivity<SceneChangePresenter, ActivityModeSwitchBinding> implements SceneChangeContract.IView {

    private String mDeviceName;
    private DefaultBean mDefault;
    private SceneChangeAdapter mAdapter;
    private SendAutoCommand mSend;
    private int mPosition = -1;
    private int mDeleteSize = 0;
    private String mOutputCode;
    private String mAutoCode;
    private AutomationBean mAutomation;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mode_switch;
    }

    @Override
    protected void initialize() {
        super.initialize();
        long mDefaultId = getIntent().getLongExtra(CommonId.KEY_RECOMMEND_ID, -1);
        mDefault = DefaultDaoUtil.getInstance().getDefaultDao().queryById(mDefaultId);
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        DeviceInfoBean deviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
        mSend = new SendAutoCommand(this, deviceInfoBean);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new SceneChangePresenter(mContext, mDeviceName);
    }

    @Override
    protected void initView() {
        super.initView();
        mAdapter = new SceneChangeAdapter(mContext);
        mAdapter.setModeButton(true);
        mDBind.rvSceneList.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        mPresent.getSceneList();
        refreshView();
        LiveDataBus.get().with(CommonId.KEY_MODIFY, Integer.class).observe(this, integer -> {
            mPosition = integer;
            String sceneId = CoderUtils.setCodeSupplement1Byte(Integer.toHexString(integer));
            mOutputCode = "FFFF000051" + sceneId;
            mDefault.setOutputCode(mOutputCode);
            String finalCode = CoderUtils.getNewCode(mDefault);
            String finalCRC = ByteUtil.stringToCRC(finalCode);
            mAutoCode = finalCode + finalCRC;
            if (mAutomation!=null){
                String firstCode = CoderUtils.setCodeSupplement2Byte(Integer.toHexString(mAutomation.getMid()));
                String mDefaultCode = firstCode + mAutoCode;
                mSend.updateAutomation(mDefaultCode.toUpperCase());
            }else {
                String firstCode =  "FFFF";
                String mDefaultCode = firstCode + mAutoCode;
                mSend.increaseAutomation(mDefaultCode.toUpperCase());
            }
            showProgressDialog();
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivModeBack.setOnClickListener(view -> finish());
        mDBind.btModeDelete.setOnClickListener(view -> {
            mDeleteSize = 0;
            showProgressDialog();
            new Thread(() -> {
                List<AutomationBean> mList = AutomationDaoUtil.getInstance().findAutomationByDefault(mDefault);
                if (mList!=null){
                    for (AutomationBean automation : mList) {
                        mSend.deleteAutomation(automation.getMid());
                    }
                }
            }).start();
        });
        mDBind.rvSceneList.setOnLoadListener(new CustomRefreshView.OnLoadListener() {
            @Override
            public void onRefresh() {
                mDBind.rvSceneList.complete();
            }

            @Override
            public void onLoadMore() {
                mDBind.rvSceneList.complete();
            }
        });
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                dismissProgressDialog();
                if (event.getData_str1().length() == 9) {
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    String code = event.getData_str2();
                    if (cmd == SiterCommand.INCREASE_AUTOMATION || cmd == SiterCommand.MODIFY_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            if (mDefault!=null){
                                DefaultDaoUtil.getInstance().getDefaultDao().update(mDefault);
                                runOnUiThread(()-> {
                                    mAdapter.setPosition(mPosition);
                                    mDBind.btModeDelete.setVisibility(View.VISIBLE);
                                });
                            }
                            String finalCode = code.substring(3) + mAutoCode;
                            ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
                            Runnable runnable = () -> CoderUtils.analysisFullCode(finalCode.toUpperCase(), mDeviceName);
                            mExecutorService.execute(runnable);
                        }
                    }else if (cmd == SiterCommand.DELETE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code)) {
                            if (mDeleteSize == 0) {
                                if (mAutomation != null) {
                                    AutomationDaoUtil.getInstance().deleteByRecommendId(mDefault);
                                }
                                runOnUiThread(()->{
                                    refreshView();
                                    showToast(getString(R.string.delete_success));
                                });
                            }
                            mDeleteSize++;
                        }else {
                            showToast(getString(R.string.failed));
                        }
                    }
                }
            }
        });
    }

    private void refreshView(){
        mAutomation = AutomationDaoUtil.getInstance().findAutomationByRecommendId(mDefault);
        if (mAutomation == null){
            mAdapter.setPosition(-1);
            mDBind.btModeDelete.setVisibility(View.GONE);
        }else {
            if (mAutomation.getCode()!=null){
                String code = mAutomation.getCode();
                String sceneId = code.substring(code.length()-6, code.length()-4);
                int position = Integer.parseInt(sceneId, 16);
                mAdapter.setPosition(position);
            }
            mDBind.btModeDelete.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showSceneList(List<SceneBean> scene) {
        mAdapter.setList(scene);
    }

    @Override
    public void showToastMsg(String msg) {
        showToast(msg);
    }

    @Override
    public void showProgress() {
        showProgressDialog();
    }

    @Override
    public void setDeleteSceneId(int sceneId) {

    }
}
